from machine import Pin
import utime

# 创建KEY对象
key_pins = [14, 27, 26, 25]
keys = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in key_pins]

# 创建LED对象
led_pins = [16, 17, 5, 18]
leds = [Pin(pin, Pin.OUT, value=0) for pin in led_pins]

# 创建继电器对象
relay = Pin(33, Pin.OUT, value=0)

def key_scan():
    temp = 0
    if keys[0].value() == 0:
         temp = 1 
    elif keys[1].value() == 0:
         temp = 2
    elif keys[2].value() == 0:
         temp = 3
    elif keys[3].value() == 0:
        temp = 4
    return temp

if __name__ == "__main__":
    key_old = 0
    leds_val = [0] * 4
    relay_val = 0
        
    while True:
        # 获取键码
        key_num = key_scan()
        key_down = key_num & (key_num ^ key_old)
        key_up = ~key_num & (key_num ^ key_old)
        key_old = key_num
        if key_down != 0:
            print(f"key_down: {key_down}")
            # LED控制
            idx = key_down - 1
            leds_val[idx] = not leds_val[idx]
            leds[idx].value(leds_val[idx])
            # 继电器控制
            relay_val = not relay_val
            relay.value(relay_val)
        
        
    
    